<template>
  <div class="h-full">
    <!-- 工具栏 -->
    <div class="flex items-center justify-between p-3 bg-white rounded mb-3">
      <!-- 左侧操作按钮 -->
      <div class="flex items-center space-x-2">
        <NButton v-if="canModify" type="primary" @click="handleAdd">
          <template #icon>
            <SvgIcon icon="mdi:plus" />
          </template>
          添加品牌
        </NButton>
      </div>

      <!-- 右侧搜索 -->
      <div class="flex items-center">
        <NInput v-model:value="searchText" placeholder="请输入品牌名字" style="width: 300px" clearable
          @keydown.enter="handleSearch" @clear="handleSearch">
          <template #suffix>
            <NButton text type="primary" @click="handleSearch">
              <template #icon>
                <SvgIcon icon="mdi:magnify" />
              </template>
            </NButton>
          </template>
        </NInput>
      </div>
    </div>

    <!-- 品牌列表表格 -->
    <div class="bg-white p-2 rounded" style="height: calc(100% - 80px);">
      <NDataTable :columns="columns" :data="brandList" :loading="loading"
        :max-height="'calc(100vh - 280px)'" :scroll-x="800" empty-text="暂无品牌数据" striped />
    </div>

    <!-- 品牌表单弹窗 -->
    <BrandForm v-model:visible="formVisible" :edit-data="editData" @success="handleFormSuccess" />
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NButton, useDialog, useMessage } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';
import BrandForm from './modules/brand-form.vue';
import type { GoodsBrand } from './modules/types';

// 页面组件名称
defineOptions({ name: 'GoodBrand' });

// Hooks
const message = useMessage();
const dialog = useDialog();
const authStore = useAuthStore();

// 响应式数据
const loading = ref(false);
const brandList = ref<GoodsBrand[]>([]);
const searchText = ref('');
const formVisible = ref(false);
const editData = ref<GoodsBrand | null>(null);

// 权限控制
const rights = computed(() => authStore.getInventoryRights());
const canSee = computed(() => rights.value?.brand?.see ?? false);
const canModify = computed(() => rights.value?.brand?.modify ?? false);
const canRemove = computed(() => rights.value?.brand?.remove ?? false);

// 表格列配置
const columns: DataTableColumns<GoodsBrand> = [
  {
    key: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    render: (row, index) => index + 1
  },
  {
    key: 'name',
    title: '品牌名称',
    minWidth: 150
  },
  {
    key: 'beizhu',
    title: '备注',
    minWidth: 200,
    render: (row) => row.beizhu || '-'
  },
  {
    key: 'actions',
    title: '操作',
    width: 140,
    align: 'center',
    fixed: 'right',
    render: (row) => {
      const actions = [];

      if (canModify.value) {
        actions.push(
          h(
            NButton,
            {
              type: 'primary',
              text: true,
              onClick: () => handleEdit(row)
            },
            { default: () => '编辑' }
          )
        );
      }

      if (canRemove.value) {
        actions.push(
          h(
            NButton,
            {
              type: 'error',
              text: true,
              onClick: () => handleDelete(row)
            },
            { default: () => '删除' }
          )
        );
      }

      return h('div', { class: 'flex items-center justify-center space-x-4' }, actions);
    }
  }
];

// 权限检查
function checkPermission() {
  if (!canSee.value) {
    window.$message?.error('暂无查看权限');
    return false;
  }
  return true;
}

// 获取品牌列表
async function getBrandList() {
  if (!checkPermission()) return;

  loading.value = true;

  const response = await InventoryGoods.getBrandList({
    searchText: searchText.value
  });

  if (response && !response.error && response.data) {
    brandList.value = response.data || [];
  } else {
    brandList.value = [];
  }

  loading.value = false;
}

// 搜索
function handleSearch() {
  getBrandList();
}

// 添加品牌
function handleAdd() {
  if (!canModify.value) {
    window.$message?.error('暂无新增权限');
    return;
  }

  editData.value = null;
  formVisible.value = true;
}

// 编辑品牌
function handleEdit(row: GoodsBrand) {
  if (!canModify.value) {
    window.$message?.error('暂无编辑权限');
    return;
  }

  editData.value = row;
  formVisible.value = true;
}

// 删除品牌
function handleDelete(row: GoodsBrand) {
  if (!canRemove.value) {
    window.$message?.error('暂无删除权限');
    return;
  }

  dialog.warning({
    title: '提示',
    content: `是否删除品牌"${row.name}"？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const response = await InventoryGoods.removeBrand(row.objectId);

      if (response && !response.error && response.data) {
        window.$message?.success('删除成功');
        getBrandList();
      }
    }
  });
}

// 表单操作成功
function handleFormSuccess() {
  getBrandList();
}

// 初始化
onMounted(() => {
  getBrandList();
});
</script>

<style scoped>
.space-x-2> :not([hidden])~ :not([hidden]) {
  margin-left: 8px;
}

:deep(.n-data-table .n-data-table-th) {
  background-color: #fafafa;
}

:deep(.n-data-table .n-data-table-td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.n-input .n-input-wrapper) {
  padding-right: 0;
}
</style>